package cn.com.coding.app;

import cn.com.coding.common.lang.ResT;
import cn.com.coding.common.utils.PageUtil;
import cn.com.coding.system.domin.SysRoleEntity;
import cn.com.coding.system.domin.SysUserRoleEntity;
import cn.com.coding.system.domin.UserCardEntity;
import cn.com.coding.system.domin.UserInfoEntity;
import cn.com.coding.system.service.UserInfoService;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 用户
 *
 * @author mxz
 */
@Api(tags = "用户信息模块")
@RestController
@RequestMapping("cat/userInfo")
public class UserInfoController extends BaseController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public ResT list(@RequestParam Map<String, Object> params) {
        PageUtil page = userInfoService.queryPage(params);

        return ResT.ok().put("page", page);
    }


    /**
     * 获取某个用户信息
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/info/{pid}", method = RequestMethod.GET)
    public ResT userInfo(@PathVariable("pid") String pid) {

        UserInfoEntity userInfoEntity = userInfoService.getById(pid);

        List<SysRoleEntity> roles = sysRoleService.listRolesByUserPid(pid);

        userInfoEntity.setSysRoles(roles);

        return ResT.ok().setData(MapUtil.builder().put("userInfo", userInfoEntity).build());
    }

    /**
     * 查询是否重名
     */
    @RequestMapping(value = "/findUserName", method = RequestMethod.POST)
    public ResT findUserName(@RequestBody String userName) {
        UserInfoEntity userInfoEntity = userInfoService.getOne(new QueryWrapper<UserInfoEntity>().eq("user_name", userName));
        if (userInfoEntity != null) return ResT.error(208, "已存在");
        return ResT.ok().setData(MapUtil.builder().put("userInfo", userInfoEntity).build());
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public ResT save(@RequestBody UserInfoEntity userInfo) {
        userInfoService.save(userInfo);

        return ResT.ok();
    }

    /**
     * 用户注册
     *
     * @param userInfo
     * @return
     */
    @RequestMapping("/register")
    public ResT register(@RequestBody UserInfoEntity userInfo) {
        String password = bCryptPasswordEncoder.encode(userInfo.getPassword());
        userInfo.setPassword(password);
        userInfo.setUserStatus(1);
        userInfoService.save(userInfo);
        UserCardEntity userCard = new UserCardEntity();
        userCard.setUserPid(userInfo.getPid());
        userCard.setCardStatus(0);
        userCardService.save(userCard);
        LocalDate date = LocalDate.now();
        redisUtil.hincr("mxz_user_register_record", String.valueOf(date), 1);
        return ResT.ok().setData(MapUtil.builder().put("userInfo", userInfo).build());
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public ResT update(@RequestBody UserInfoEntity userInfo) {
        userInfoService.updateById(userInfo);

        return ResT.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public ResT delete(@RequestBody String[] pids) {
        List<UserInfoEntity> list = new ArrayList<>(pids.length);

        Arrays.stream(pids).forEach(e -> {
            UserInfoEntity userInfoEntity = userInfoService.getById(e);
            userInfoEntity.setUserStatus(2);
            list.add(userInfoEntity);
        });

        userInfoService.saveOrUpdateBatch(list);

        return ResT.ok();
    }

    /**
     * 用户角色关联
     *
     * @param userPid
     * @param rolePids
     * @return
     */
    @Transactional
    @PostMapping("/role/{userPid}")
//    @PreAuthorize("hasAuthority('sys:user:role')")
    public ResT rolePerm(@PathVariable("userPid") String userPid, @RequestBody String[] rolePids) {

        List<SysUserRoleEntity> userRoles = new ArrayList<>();

        Arrays.stream(rolePids).forEach(r -> {
            SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
            sysUserRole.setRolePid(r);
            sysUserRole.setUserPid(userPid);

            userRoles.add(sysUserRole);
        });

        // 移除之前的权限
        sysUserRoleService.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_pid", userPid));

        sysUserRoleService.saveBatch(userRoles);
        // 删除缓存
        UserInfoEntity userEntity = userInfoService.getById(userPid);
        // 删除缓存 用的还是 sysUserService 尽量能够复用
        sysUserService.clearUserAuthorityInfo(userEntity.getUserName());

        return ResT.ok();
    }

}
